package com.xu.tasks.observer;

import com.alibaba.fastjson.JSON;
import com.xu.pojo.MovieDetail;
import com.xu.service.MovieDetailService;
import com.xu.tasks.MovieDetailPageProcessor;
import com.xu.uitls.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class MovieDetailObserver {
    @Autowired
    private MovieDetailService movieDetailService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    private Set<MovieDetailPageProcessor> movieDetailPageProcessorSet = new HashSet<>();

    public Set<MovieDetailPageProcessor> getMovieDetailPageProcessorSet() {
        return movieDetailPageProcessorSet;
    }

    public void setMovieDetailPageProcessorSet(Set<MovieDetailPageProcessor> movieDetailPageProcessorSet) {
        this.movieDetailPageProcessorSet = movieDetailPageProcessorSet;
    }

    public void addMovieDetailPageProcessor(MovieDetailPageProcessor movieDetailPageProcessor){
        movieDetailPageProcessorSet.add(movieDetailPageProcessor);
    }

    public void removeMovieDetailPageProcessor(MovieDetailPageProcessor movieDetailPageProcessor){
        movieDetailPageProcessorSet.remove(movieDetailPageProcessor);
    }

    public void doNotify() throws InterruptedException {
        Iterator<MovieDetailPageProcessor> iterator = movieDetailPageProcessorSet.iterator();

        while (iterator.hasNext()){
            MovieDetailPageProcessor movieDetailPageProcessor = iterator.next();
            MovieDetail movieDetail = movieDetailPageProcessor.exec();
            boolean flag = movieDetailService.insertMovieDetail(movieDetail);

            if (flag){
                iterator.remove();
                redisTemplate.opsForList().rightPush("movieDetails",JSON.toJSONString(movieDetail));
            }
            TimeUnit.SECONDS.sleep((long) (Math.random() * 10));
        }

        redisTemplate.expire("movieDetails",50,TimeUnit.MINUTES);
        System.out.println("失败任务数：" + movieDetailPageProcessorSet.size() + " 将在40分钟后尝试爬取");
//        for (MovieDetailPageProcessor movieDetailPageProcessor : movieDetailPageProcessorSet) {
//            MovieDetail movieDetail = movieDetailPageProcessor.exec();
//            movieDetailService.insertMovieDetail(movieDetail);
//            try {
//                int time = (int) (Math.random() * 10);
//                TimeUnit.SECONDS.sleep(time);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
    }
}
